<template>
    <view class="page-verification-code" :style="`padding-top: ${statusBarHeight}px`">
        <view class="top-header">
            <view class="cancel" @click="handleBack">返回</view>
            <view class="title">{{ pageTitle }}</view>
            <view style="opacity: 0">返回</view>
        </view>
        <view class="content">
            <view class="welcome-title">请输入验证码</view>
            <!-- 手机号提示 -->
            <view class="subtitle"><text>{{ operationType === 'unbind' ? '解绑手机号' : '绑定手机号' }}：{{ formatPhoneNumber }}</text></view>
            
            <!-- 验证码输入框 -->
            <view class="code-container">
                <input v-for="(item, index) in codeArray" :key="index" :ref="(el) => setInputRef(el, index)"
                    class="code-input" type="number" inputmode="numeric" maxlength="1" v-model="codeArray[index]"
                    @input="handleInput(index, $event)" @focus="handleFocus(index)"
                    @keydown="handleKeyDown(index, $event)" :focus="currentFocusIndex === index" />
            </view>

            <!-- 重新获取验证码 -->
            <view class="resend-container">
                <text v-if="countdown > 0" class="resend-text">{{ countdown }}秒后重新获取</text>
                <text v-else class="resend-text active" @click="handleResend">重新获取验证码</text>
            </view>
        </view>
        <!-- 验证按钮 -->
        <view class="primary-button" :class="{ disabled: !isCodeComplete }" @click="handleVerify">
            {{ operationType === 'unbind' ? '解绑' : '绑定' }}
        </view>
    </view>
</template>

<script setup>
import { bindPhone, unBindPhone } from '@/api/user'
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed, onMounted, nextTick } from "vue";
import store from "@/store/index.js";
const statusBarHeight = computed(() => store.state.systemInfo.statusBarHeight);

// 页面参数
const operationType = ref('bind'); // 默认为绑定操作
const phoneNumber = ref(''); // 手机号
const pageTitle = computed(() => operationType.value === 'unbind' ? '解绑手机号' : '绑定手机号');

// 格式化手机号显示
const formatPhoneNumber = computed(() => {
    if (!phoneNumber.value) return '';
    return phoneNumber.value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
});

// 验证码数组（4位）
const codeArray = ref(["", "", "", ""]);
const currentFocusIndex = ref(0);
const countdown = ref(60);
const inputRefs = ref([]);

// 计算属性：验证码是否输入完整
const isCodeComplete = computed(() => {
    return codeArray.value.every((item) => item !== "");
});



// 处理输入
const handleInput = (index, e) => {
    const value = e.detail.value;

    // 过滤非数字字符
    if (!/^\d*$/.test(value)) {
        codeArray.value[index] = "";
        return;
    }

    // 自动聚焦到下一个输入框
    if (value && index < codeArray.value.length - 1) {
        currentFocusIndex.value = index + 1;
        nextTick(() => {
            inputRefs.value[index + 1].focus();
        });
    }
};


const handleKeyDown = (index, e) => {
    const keyCode = e.keyCode || e.detail?.keyCode || 0;

    if (keyCode === 8) {
        // Backspace键
        // 如果当前框为空，且不是第一个框，则删除前一个框的内容并聚焦
        if (!codeArray.value[index] && index > 0) {
            codeArray.value[index - 1] = "";
            currentFocusIndex.value = index - 1;

            // 确保DOM更新后执行聚焦
            nextTick(() => {
                inputRefs.value[index - 1].focus();
            });
        }
    }
};

// 处理聚焦
const handleFocus = (index) => {
    currentFocusIndex.value = index;

    // 聚焦时选中文本方便重新输入
    nextTick(() => {
        const input = inputRefs.value[index];
        if (input) {
            input.setSelectionRange(0, 1);
        }
    });
};

// 处理返回
const handleBack = () => {
    uni.navigateBack();
};

// 发送验证码
const sendVerificationCode = () => {
    const api = operationType.value === 'unbind' 
        ? '/api/user/sendUnbindSmsCode' 
        : '/api/user/sendBindSmsCode';
    
    uni.showLoading({ title: '发送中...' });
    
    // 这里应该调用实际的API
    // 模拟API调用
    setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
            title: "验证码已发送",
            icon: "success"
        });
        
        // 启动倒计时
        countdown.value = 60;
        startCountdown();
    }, 1000);
};

// 处理验证
const handleVerify = () => {
    if (!isCodeComplete.value) {
        uni.showToast({ icon: "error", title: "请输入验证码" });
        return;
    }

    const verifyCode = codeArray.value.join("");
    uni.showLoading({
        title: operationType.value === 'unbind' ? "解绑中..." : "绑定中...",
    });

    const api = operationType.value === 'unbind' 
        ? '/api/user/unbindPhone' 
        : '/api/user/bindPhone';
    
    // 模拟API请求
    setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
            title: operationType.value === 'unbind' ? "手机号解绑成功" : "手机号绑定成功",
            icon: "success",
        });

        // 操作成功后返回设置页面
        setTimeout(() => {
            uni.navigateBack({
                delta: operationType.value === 'unbind' ? 1 : 2});
        }, 1000);
    }, 1500);
};

// 处理重新获取
const handleResend = () => {
    if (countdown.value > 0) return;

    // 发送验证码
    sendVerificationCode();
    
    // 清空验证码
    codeArray.value = ["", "", "", ""];
    currentFocusIndex.value = 0;
};

// 倒计时
const startCountdown = () => {
    const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);
};

// 初始化输入框引用
const setInputRef = (el, index) => {
    if (el) {
        inputRefs.value[index] = el;
    }
};

onLoad((opt) => {
    // 解析页面类型参数
    operationType.value = opt.type;
    // 解绑时获取要解绑的手机号
    phoneNumber.value = opt.phone;

    // 发送初始验证码 如果是绑定 则不需要发送
    if (operationType.value === 'unbind') {
        sendVerificationCode();
    } else {
        startCountdown();
    }
})
</script>

<style lang="scss">
.page-verification-code {
    .content {
        padding: 0 50px;
        box-sizing: border-box;
    }
}

.top-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px 10px;
    border-bottom: 1px solid #e4e4e499;
    box-sizing: border-box;
    margin-bottom: 15px;

    .cancel {
        font-size: 15px;
        font-weight: 300;
        letter-spacing: 0px;
        line-height: 20px;
        color: rgba(153, 153, 153, 1);
        text-align: left;
        vertical-align: top;
    }

    .title {
        font-size: 17px;
        font-weight: 600;
        letter-spacing: 0px;
        line-height: 22px;
        color: rgba(21, 21, 34, 1);
        text-align: center;
        vertical-align: top;
    }
}

.back {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60rpx;
    height: 60rpx;
    border-radius: 10rpx;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(232, 236, 244, 1);
}

.skip {
    width: 48px;
    height: 29px;
    font-size: 24px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 28.13px;
    color: rgba(0, 152, 255, 1);
    text-align: center;
    vertical-align: top;
}

.welcome-title {
    margin: 68px auto 20px;
    font-size: 32px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 18.75px;
    color: rgba(0, 0, 0, 1);
    vertical-align: bottom;
}

.subtitle {
    width: 80vw;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 80rpx;
}

.code-container {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 60rpx;
}

.code-input {
    width: 100rpx;
    height: 100rpx;
    text-align: center;
    font-size: 48rpx;
    border: 2rpx solid #e8ecf4;
    border-radius: 12rpx;

    &:focus {
        border-color: #35c2c1;
    }
}

.resend-container {
    margin-bottom: 80rpx;
    width: 100%;
    text-align: center;
}

.resend-text {
    font-size: 28rpx;
    color: #999;

    &.active {
        color: #007aff;
    }
}

.primary-button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: calc(100vw - 50px);
    height: 48px;
    margin: 0 auto;
    opacity: 1;
    border-radius: 8.02px;
    background: #5d5fef;
    box-shadow: 0px 0px 0px 6.42px #ffffff26;

    font-size: 18px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 21.1px;
    color: rgba(255, 255, 255, 1);
    text-align: center;

    &.disabled {
        opacity: 1;
        background-color: #eee;
    }
}
</style>
